package demo1;

import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
import org.apache.zookeeper.ZooKeeper;

import java.io.IOException;
import java.util.concurrent.CountDownLatch;

/**
 * --------神兽出没--------/
 *   ┌─┐     ┌─┐
 * ┌─┘─┴─────┘─┴─┐
 * │      ─      │
 * │  ┬─┘   └─┬  │
 * │             │
 * │      ┴      │  Code is far away from bug with the animal protecting
 * └───┐      ┌──┘  神兽保佑,代码无bug
 *     │      │
 *     │      └──────┐
 *     │             ├┐
 *     │             ┌┘
 *     └┐ ┐ ┌───┬─┐ ┌┘
 *      │ ┤ ┤   │ ┤ ┤
 *      └─┴─┘   └─┴─┘
 * --------感觉萌萌哒--------/
 *
 * zk实现Watcher接口（Watcher接口为zk的使用接口）
 * @author wuyoushan
 * @date 2018/5/3
 */
public class AbstractZooKeeper implements Watcher{

    //缓存时间
    private static final int SESSION_TIME   = 2000;
    ZooKeeper zooKeeper;
    private CountDownLatch countDownLatch=new CountDownLatch(1);

    /**
     * zk的连接
     *
     * @param hosts hosts
     */
    public void connect(String hosts) throws IOException, InterruptedException {
        zooKeeper = new ZooKeeper(hosts, SESSION_TIME, this);
        //等待连接通过
        countDownLatch.await();
    }

    /**
     * 监控触发事件
     *
     * @param watchedEvent WatchedEvent
     */
    @Override
    public void process(WatchedEvent watchedEvent) {
        if (watchedEvent.getState() == Event.KeeperState.SyncConnected){
            countDownLatch.countDown();
        }
    }


    /**
     * 关闭连接
     */
    public void close() throws InterruptedException {
        zooKeeper.close();
    }
}
